package mxmf.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DateUtil {
  
    private static final String date_format = "yyyyMMdd";
    private static final String date_format1 = "yyyy-MM-dd HH:mm:ss";
    private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>(); 
    private static final Logger logger = LoggerFactory.getLogger(DateUtil.class);
    public static DateFormat getDateFormat(String formatter)   
    {  
        DateFormat df = threadLocal.get();  
        if(df==null){  
            df = new SimpleDateFormat(formatter);
            df.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            threadLocal.set(df);  
        }  
        return df;  
    }  

    public static String formatDate(Date date)  {
        return getDateFormat(date_format).format(date);
    }
    
    public static String formatDateStr(Date date)  {
        return getDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
    }
    
    public static String formatStr(long date)  {
        if(EmptyUtil.isEmpty(date)) {
            return "";
        }
        return String.valueOf(getDateFormat(date_format1).format(new Date(Long.valueOf(date))));
    }
    
    public static Date parse(String strDate)  {
        try {
			return getDateFormat(date_format).parse(strDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			logger.error("日期【"+strDate+"】格式转换错误，【"+e.getMessage()+"】");
		}
		return null;
    } 
    
    public static Date dayEnd(Date date) {
        Calendar dayEnd = Calendar.getInstance();
        dayEnd.setTime(date);
        dayEnd.set(Calendar.HOUR, 23);
        dayEnd.set(Calendar.MINUTE, 59);
        dayEnd.set(Calendar.SECOND, 59);
        dayEnd.set(Calendar.MILLISECOND, 999);
        return dayEnd.getTime();
    }
}
